//
//  HMTextView.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class HMTextView: UITextView {
    
    var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func textDidChange() {
        placeholderLabel.isHidden = hasText
    }
    
    private func setupUI(){
        // 添加占位文字的label
        addSubview(placeholderLabel)
        
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self).offset(5)
            make.top.equalTo(self).offset(8)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderLabel.snp_updateConstraints { (make) in
            make.width.lessThanOrEqualTo(self.frame.width - 2 * 5)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel(textColor: UIColor.lightGray, fontSize: 12)
        label.numberOfLines = 0
        return label
    }()
}
